package com.besttone.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.FieldStatsInfo;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.params.StatsParams;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.solr.common.cloud.ZkStateReader;

public class Sms2SolrUtil {
	private static Log _log = LogFactory.getLog(Sms2SolrUtil.class);
	private static CloudSolrServer cloudSolrServer;
	/**
	 * 获取CloudSolrServer
	 *
	 * @param zkHost
	 * @return
	 */
	private static synchronized CloudSolrServer getCloudSolrServer(
			final String zkHost) {
		if (cloudSolrServer == null) {
			try {
				_log.info("创建cloudSolrServer");
				cloudSolrServer = new CloudSolrServer(zkHost);
			} catch (Exception e) {
				_log.info("cloudSolrServer创建异常:" + e);
			}
		}
		return cloudSolrServer;
	}
	/**
	 * 连接CloudSolrServer
	 */
	private static void connectCloudSolrServer(String defaultConnection) {
		cloudSolrServer = getCloudSolrServer(PropertieUtils
				.getProperty("zkHost"));
		_log.info("The Cloud SolrServer Instance has benn created!");
		cloudSolrServer.setDefaultCollection(PropertieUtils
				.getProperty(defaultConnection));
		cloudSolrServer.setZkClientTimeout(Integer.valueOf(PropertieUtils
				.getProperty("zkClientTimeout")));
		cloudSolrServer.setZkConnectTimeout(Integer.valueOf(PropertieUtils
				.getProperty("zkConnectTimeout")));
		try{
			cloudSolrServer.connect();
		}catch(Exception e){
			_log.info("cloundSolrServer connection exception:"+e);
		}
		_log.info("The cloud Server has been connected !!!!");
		/**ZkStateReader zkStateReader = cloudSolrServer.getZkStateReader();
		 ClusterState cloudState = zkStateReader.getClusterState();
		 System.out.println(cloudState);**/
	}

	/**
	 * 查询短信详情索引
	 *
	 * @param querySql
	 * @param currentPage
	 * @param perPageSize
	 * @return
	 */
	public static SolrDocumentList search(String querySql, Integer currentPage,
										  Integer perPageSize) {

		SolrQuery query = new SolrQuery();
		query.setQuery(querySql);
		System.out.println("querySql:"+querySql);
		query.setStart((currentPage - 1) * perPageSize);
		query.setRows(perPageSize);
		query.setFields("mt_msgid,sms_content,target_number,send_number,mt_total,call_status,"
				+ "send_time,target_time,mt_status,mt_errcode,template_code");// 查询字段
		query.setSort("send_time", ORDER.desc);
		try {

			connectCloudSolrServer(PropertieUtils
			.getProperty("collectionSmsLog"));
			cloudSolrServer.setDefaultCollection(PropertieUtils
					.getProperty("collectionSmsLog"));
			QueryResponse response = cloudSolrServer.query(query);
			SolrDocumentList docs = response.getResults();
			_log.info("文档个数：" + docs.getNumFound());
			_log.info("查询时间：" + response.getQTime());
			//cloudSolrServer.shutdown();
			return docs;
		} catch (SolrServerException e) {
			_log.info("SolrServer异常：" + e);
		} catch (Exception e) {
			_log.info("Solr查询异常：" + e);
		}
		return null;
	}
	/**
	 * 查询短信按天统计索引
	 *
	 * @param querySql
	 * @return
	 */
	public static SolrDocumentList searchBusinessTypeByDay(String querySql) {
		SolrQuery query = new SolrQuery();
		query.setQuery(querySql);
		//query.setStart((currentPage - 1) * perPageSize);
		//query.setRows(perPageSize);
		query.setFields("id");// 查询字段
		try {
			connectCloudSolrServer(PropertieUtils
					.getProperty("collectionSmsDay"));
			//cloudSolrServer.setDefaultCollection("collectionSmsDay");
			QueryResponse response = cloudSolrServer.query(query);
			SolrDocumentList docs = response.getResults();
			_log.info("文档个数：" + docs.getNumFound());
			_log.info("查询时间：" + response.getQTime());
			return docs;
		} catch (SolrServerException e) {
			_log.info("SolrServer异常：" + e);
		} catch (Exception e) {
			_log.info("Solr查询异常：" + e);
		}
		// cloudSolrServer.shutdown();
		return null;

	}

	/**
	 * 按busi_type分组聚合统计(类似SQL:sum(cnts) group by(busi_type))
	 * TODO 可能满足不了需求,因为每个busi_type查询的条件不同，不都是按照template_code或send_number查询的
	 * @param querySql
	 * @return map<busi_type,sum>
	 */
	private static final String FIELD_CNTS = "cnts";
	private static final String FACET_BUSI_TYPE = "busi_type";
	public static Map<String,Long> searchSumByDay(String querySql) {
		SolrQuery query = new SolrQuery();
		query.setQuery(querySql);
		query.setRows(0);
		query.set(StatsParams.STATS,true);
		query.set(StatsParams.STATS_FIELD,FIELD_CNTS);
		query.set(StatsParams.STATS_FACET,FACET_BUSI_TYPE);
		Map<String,Long> facetMap=new HashMap<String, Long>();
		try {
			connectCloudSolrServer(PropertieUtils
					.getProperty("collectionSmsDay"));
			QueryResponse response = cloudSolrServer.query(query);
			FieldStatsInfo fieldOneStats=response.getFieldStatsInfo().get(FIELD_CNTS);
			Map<String, List<FieldStatsInfo>> facetsMap=fieldOneStats.getFacets();
			List<FieldStatsInfo> infoList=facetsMap.get(FACET_BUSI_TYPE);
			for(FieldStatsInfo fieldStatsInfo:infoList){
				facetMap.put(fieldStatsInfo.getName(),(new Double((Double)fieldStatsInfo.getSum()).longValue()));
			}
		} catch (SolrServerException e) {
			_log.info("SolrServer异常：" + e);
		} catch (Exception e) {
			_log.info("Solr查询异常：" + e);
		}
		return facetMap;
	}
	/**
	 * 根据sql语句聚合查询sum
	 * @param querySql
	 * @return map<busi_type,sum>
	 */
	public static long searchSumByBusinessTypeAndDay(String querySql) {
		SolrQuery query = new SolrQuery();
		query.setQuery(querySql);
		query.setRows(0);
		query.set(StatsParams.STATS,true);
		query.set(StatsParams.STATS_FIELD,"cnts");
		try {
			connectCloudSolrServer(PropertieUtils
					.getProperty("collectionSmsDay"));
			QueryResponse response = cloudSolrServer.query(query);
			FieldStatsInfo fieldOneStats=response.getFieldStatsInfo().get(FIELD_CNTS);
			return (new Double((Double)fieldOneStats.getSum()).longValue());
		} catch (SolrServerException e) {
			_log.info("SolrServer异常：" + e);
		} catch (Exception e) {
			_log.info("Solr查询异常：" + e);
		}
		return 0;
	}
	public static void main(String[] args) {
		SolrServer server = new HttpSolrServer("http://dn7.hadoop:8983/solr/");
		SolrQuery query = new SolrQuery();
		query.setQuery( "send_number:15335599797" );
		//QueryResponse rsp = server.query(query);
	}
}
